<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <%@include file="/WEB-INF/pages/include/base_css.jsp"%>
    <style>
        .tree li {
            list-style-type: none;
            cursor:pointer;
        }
        table tbody tr:nth-child(odd){background:#F4F4F4;}
        table tbody td:nth-child(even){color:#C00;}
    </style>
</head>

<body>

<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
    <div class="container-fluid">
        <div class="navbar-header">
            <div><a class="navbar-brand" style="font-size:32px;" href="#">众筹平台 - 角色维护</a></div>
        </div>
        <%@include file="/WEB-INF/pages/include/manager_loginbar.jsp"%>
    </div>
</nav>

<div class="container-fluid">
    <div class="row">
        <div class="col-sm-3 col-md-2 sidebar">
            <%@include file="/WEB-INF/pages/include/manager_menu.jsp"%>
        </div>
        <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title"><i class="glyphicon glyphicon-th"></i> 数据列表</h3>
                </div>
                <div class="panel-body">
                    <form class="form-inline" role="form" style="float:left;">
                        <div class="form-group has-feedback">
                            <div class="input-group">
                                <div class="input-group-addon">查询条件</div>
                                <input class="form-control has-success" name="condition" type="text" placeholder="请输入查询条件">
                            </div>
                        </div>
                        <button type="button" id="queryRolesBtn" class="btn btn-warning"><i class="glyphicon glyphicon-search"></i> 查询</button>
                    </form>
                    <button type="button" id="batchDeleteRolesBtn" class="btn btn-danger" style="float:right;margin-left:10px;"><i class=" glyphicon glyphicon-remove"></i> 删除</button>
                    <button type="button" class="btn btn-primary" style="float:right;" id="addRoleBtn"><i class="glyphicon glyphicon-plus"></i> 新增</button>
                    <br>
                    <hr style="clear:both;">
                    <div class="table-responsive">
                        <table class="table  table-bordered">
                            <thead>
                            <tr >
                                <th width="30">#</th>
                                <th width="30"><input type="checkbox"></th>
                                <th>名称</th>
                                <th width="100">操作</th>
                            </tr>
                            </thead>
                            <tbody>


                            </tbody>
                            <tfoot>
                            <tr >
                                <td colspan="6" align="center">
                                    <ul class="pagination">

                                    </ul>
                                </td>
                            </tr>

                            </tfoot>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
//新增角色的模态框
<div class="modal fade" id="addRoleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="exampleModalLabel">新增角色</h4>
            </div>
            <div class="modal-body">
                <form>
                    <div class="form-group">
                        <label for="recipient-name" class="control-label">角色名称:</label>
                        <input type="text" name="name" class="form-control" id="recipient-name">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" id="addRoleModalBtn" class="btn btn-primary">提交</button>
            </div>
        </div>
    </div>
</div>
//新增角色的模态框 - end
//更新角色的模态框
<div class="modal fade" id="updateRoleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="exampleModalLabel">更新角色</h4>
            </div>
            <div class="modal-body">
                <form>
                    <input type="hidden" name="id">
                    <div class="form-group">
                        <label for="recipient-name" class="control-label">角色名称:</label>
                        <input type="text" name="name" class="form-control" id="recipient-name">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" id="updateRoleModalBtn" class="btn btn-primary">提交</button>
            </div>
        </div>
    </div>
</div>
//更新角色的模态框 - end
<%@include file="/WEB-INF/pages/include/base_js.jsp"%>
<script type="text/javascript">
    //定义全局范围的变量：接收加载分页数据的当前代码
    var currentPageNum;
    var lastPages;
    /*更新角色*/
    $("tbody").delegate(".updateRoleBtn","click",function () {
       //查询点击更新的id
       var roleId = $(this).attr("roleId");
       $.ajax({
           url:"${PATH}/role/getRoleById",
           type:"GET",
           data:{"id":roleId},
           success:function (role) {
               //将查询到的结果进行回显到模态框
               $("#updateRoleModal").modal("toggle");
               $("#updateRoleModal input[name='id']").val(role.id);
               $("#updateRoleModal input[name='name']").val(role.name);

           }
       })
    });
    //更新提交至数据库
    $("#updateRoleModalBtn").click(function () {
        $.ajax({
            url:"${PATH}/role/update",
            type:"GET",
            data:$("#updateRoleModal form").serialize(),
            success:function (result) {
                if (result == "ok"){
                    //模态框关闭
                    $("#updateRoleModal").modal("toggle");
                    //跳转至最后一页
                    var condition = $("input[name='condition']").val();
                    getRoles(lastPages+1,condition);
                    //提示
                    layer.msg("更新成功");
                }
            }
        })
    });
    /*给新增用户显示模态框绑定单击事件*/
    $("#addRoleBtn").click(function () {
        $("#addRoleModal").modal("toggle");
    });
    /*给新增用户模态框绑定单击事件发送Ajax请求*/
    $("#addRoleModalBtn").click(function () {
       $.ajax({
           url:"${PATH}/role/addRole",
           type:"POST",
           data:$("#addRoleModal form").serialize(),
           success:function (result) {
                if (result == "ok"){
                    //关闭模态框
                    $("#addRoleModal").modal("toggle");
                    //跳转到最后一页
                    getRoles(currentPageNum);
                    //提示
                    layer.msg("新增成功！")
                }
           }
       })
    });
    /*
    *  全选效果
    *  1、thead下的全选框绑定单击事件
    * */
    $("thead :checkbox").click(function () {
       $("tbody :checkbox").prop("checked",this.checked);
    });
    /*
    * 2、tbody内自复选框的单击事件，需要动态委派
    * */
    $("tbody").delegate(":checkbox","click",function () {
        $("thead :checkbox").prop("checked",$("tbody :checkbox:checked").length == $("tbody :checkbox").length);
    });
    /*
    * 3、给批量删除按钮绑定单击事件
    * */
    $("#batchDeleteRolesBtn").click(function () {
        layer.confirm("您确定要删除吗？",{"title":"删除提醒:",icon:3},function () {
            //获取要选中角色的id并拼接
            var roleIdsArr = new Array();
            $("tbody :checkbox:checked").each(function () {
                //this代表正在遍历的一行记录
                roleIdsArr.push($(this).attr("roleId"));
            });

            if (roleIdsArr.length == 0){
                layer.msg("请选择你要删除的角色！");
                return ;
            }
            var roleIds = roleIdsArr.join();//用逗号分隔 [1,2,3] -> (1,2,3)
            $.ajax({
                url:"${PATH}/role/batchDeleteRoles",
                data:{"ids":roleIds},
                type:"GET",
                success:function (result) {
                    if (result == "ok"){
                        layer.msg("批量删除成功！");
                        //重新加载本页
                        var condition = $("input[name='condition']").val();
                        getRoles(currentPageNum,condition);
                    }
                }
            })
        });
        });


    /*删除单个角色 异步生成的需要动态委派一下*/
    $("tbody").delegate(".deleteRoleBtn","click",function () {
        //一定要在此获取所在行的标签
        var $tr = $(this).parents("tr");//后台响应成功需要删掉
        var roleId = $(this).attr("roleId");//提交异步请求 删除的角色id
        layer.confirm("您确定要删除吗？",{tile:"删除提示",icon:3},function () {
            $.ajax({
                type:"GET",
                url:"${PATH}/role/delete",
                data:{"id":roleId},
                success:function (result) {
                    if (result == "ok"){
                        layer.msg("删除成功！");
                        //删除当前按钮所在行的标签
                        $tr.remove();
                        if ($("tbody tr").length < 3){
                            var condition = $("input[name='condition']").val();
                            getRoles(currentPageNum,condition);
                        }
                    }
                }
            })
        })
    });

    /*带条件的分页查询*/
    $("#queryRolesBtn").click(function () {
        //获取查询条件
        var condition = $("input[name='condition']").val();
        getRoles(1,condition)
    });


    /*当浏览器访问后立即发送Ajax请求加载角色列表数据显示*/
    getRoles(1);
    function getRoles(pageNum , condition){
        //翻页时，清除全选框
        $("thead :checkbox").prop("checked",false);
        //删除之前异步生成的标签
        $("tbody").empty();
        $("tfoot ul").empty();
        $.ajax({
            url:"${PATH}/role/getRoles",
            type:"get",
            data:{"pageNum":pageNum,"condition":condition},
            success:function (pageInfo) {//请求成功之后的回调函数
                //将当前页码提升为全局变量保存
                currentPageNum = pageInfo.pageNum;
                lastPages = pageInfo.pages;
                /**
                 * {"pageNum":1,"pageSize":3,"size":3,"startRow":1,"endRow":3,"total":9,"pages":3,
                 * "list":[{"id":1,"name":"PM - 项目经理"},
                 *         {"id":2,"name":"SE - 软件工程师"},
                 *         {"id":3,"name":"PG - 程序员"}],
                 * "prePage":0,"nextPage":2,"isFirstPage":true,"isLastPage":false,"hasPreviousPage":false,"hasNextPage":true,"navigatePages":8,
                 * "navigatepageNums":[1,2,3],          "navigateFirstPage":1,"navigateLastPage":3,"firstPage":1,"lastPage":3}
                 * */

                //1.解析pageInfo.list集合，将数据显示到tbody中
                initRoleList(pageInfo);

                //2.解析pageInfo.navigateFirstPage 生成页码导航条
                //分页导航条的单击事件，请求分页数据时，只会响应分页的json。如果让浏览器发同步请求，浏览器会显示json覆盖之前的页面
                //分页导航栏超链接点击时，应该发送异步请求，成功后js接收并解析异步响应的结果，通过dom解析响应到页面中
                initRoleNav(pageInfo);

            }
        });
    }

    //处理显示角色列表
    function initRoleList(pageInfo){
        $.each(pageInfo.list, function (index) {//每遍历一次函数，调用一次function
            //this表示{"id":1,"name":"PM - 项目经理"}
            //this.id可以获取id
            $('<tr>\n' +
                ' <td>' + (index + 1) + '</td>\n' +
                ' <td><input type="checkbox"></td>\n' +
                ' <td>' + this.name + '</td>\n' +
                ' <td>\n' +
                '   <button roleId="' + this.id + '" type="button" class="btn btn-success btn-xs"><i class=" glyphicon glyphicon-check"></i></button>\n' +
                '   <button roleId="' + this.id + '" type="button" class="btn btn-primary btn-xs updateRoleBtn"><i class=" glyphicon glyphicon-pencil"></i></button>\n' +
                '   <button roleId="' + this.id + '" type="button" class="btn btn-danger btn-xs deleteRoleBtn"><i class=" glyphicon glyphicon-remove"></i></button>\n' +
                ' </td>\n' +
                '</tr>').appendTo("tbody");
        });
    }
    //处理分页
    function initRoleNav(pageInfo){
        //上一页
        if(pageInfo.isFirstPage){
            //是首页
            $('<li class="disabled"><a href="javaScript:void(0)">上一页</a></li>').appendTo("tfoot ul");
        }else{
            $('<li><a class="navA" pageNum="'+(pageInfo.pageNum-1)+'" href="javaScript:void(0)">上一页</a></li>').appendTo("tfoot ul");
        }
        //中间页 "navigatepageNums":[1,2,3]
        $.each(pageInfo.navigatepageNums,function () {
            //this代表正在遍历的页码
            if (this == pageInfo.pageNum){
                //是当前页，高亮
                $('<li class="active"><a href="javaScript:void(0)">'+this+'<span class="sr-only">(current)</span></a></li>').appendTo("tfoot ul");
            }else{
                $('<li><a class="navA" pageNum="'+(this)+'" href="javaScript:void(0)">'+this+'</a></li>').appendTo("tfoot ul");
            }
        });

        //下一页
        if (pageInfo.isLastPage){
            //是末页
            $('<li class="disabled"><a href="javaScript:void(0)">下一页</a></li>').appendTo("tfoot ul");
        }else{
            $('<li><a class="navA" pageNum="'+(pageInfo.pageNum+1)+'" href="javaScript:void(0)">下一页</a></li>').appendTo("tfoot ul");
        }
    }
    /*
    * 由于class值为navA的标签在异步请求成功之后才会解析生成，$(".navA")在js代码的主线程中会立即执行，
    * 在异步请求还未成功时，主线程需要使用就需要使用标签，所以查找失败。
    * */
    // $(".navA").click(function () {
    //     //this代表被点击的超链接
    //     var pageNum = $(this).attr("pageNum");
    //     getRoles(pageNum);
    // });
    /*
    * 动态委派：无论现有的标签还是异步加载生成的标签都可以绑定上单击事件
    * $(".navA").live("click",function{});如果页面中有新增的标签，class值为navA,则绑定单击事件
    * live方法性能差，已经淘汰
    *
    * $("祖先元素").delegate("后代元素","事件类型","事件处理函数");
    *   如果祖先内新增的标签满足后代元素的选择器字符串，则给后代元素绑定事件。
    * */
    //动态委派，处理单击事件
    $("tfoot").delegate(".navA","click",function () {
        //this代表被点击的超链接
        var pageNum = $(this).attr("pageNum");
        //获取分页查询的条件
        var condition = $("input[name='condition']").val();
        getRoles(pageNum,condition);
    });

    /*当前页面所在的菜单自动展开，模块标签高亮显示*/
    $(".list-group-item:contains('权限管理')").removeClass("tree-closed");
    $(".list-group-item:contains('权限管理') ul").show();
    $(".list-group-item:contains('权限管理') li :contains('角色维护')").css('color','red');
    $(function () {
        $(".list-group-item").click(function(){
            if ( $(this).find("ul") ) {
                $(this).toggleClass("tree-closed");
                if ( $(this).hasClass("tree-closed") ) {
                    $("ul", this).hide("fast");
                } else {
                    $("ul", this).show("fast");
                }
            }
        });
    });


    $("tbody .btn-success").click(function(){
        window.location.href = "assignPermission.html";
    });
</script>
</body>
</html>
